package com.xtool.livewallpaper.util

import android.annotation.SuppressLint
import android.net.Uri
import com.xtool.livewallpaper.base.MainApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.util.Random

@SuppressLint("Recycle")
suspend fun Uri.toInputStream() = withContext(Dispatchers.IO) {
    try {
        MainApplication.gContext.contentResolver.openInputStream(this@toInputStream)
    } catch (e: Throwable) {
        null
    }
}

suspend fun Uri.toLocalFile(): File? {
    val dir = File("${MainApplication.gContext.filesDir.absolutePath}/wallpapers")
    if (!dir.exists()) {
        dir.mkdirs()
    }
    fun createMp4Name(): String {
        return "${DateTimeUtil.formatNow("YYYY_MM_dd")}_${System.currentTimeMillis()}${Random(1000).nextInt()}.mp4"
    }

    val dest = File(dir.absolutePath, createMp4Name())
    val outputStream = withContext(Dispatchers.IO) {
        FileOutputStream(dest)
    }
    val inputStream = toInputStream() ?: return null
    inputStream flow outputStream
    return dest
}

infix fun InputStream?.flow(outputStream: OutputStream?) {
    this?.use { input ->
        outputStream?.use { output ->
            input.copyTo(output)
            output.flush()
        }
    }
}

